import Vue from "vue"
import { RECEIVE_COMMENTS, RECEIVE_GOODS, INCREASE_FOOD_COUNT, DECREASE_FOOD_COUNT, CLEAR_CART } from "./mutation-types"

export default {
  [RECEIVE_COMMENTS](state, { comments }) {
    state.comments = comments
  },
  [RECEIVE_GOODS](state, { goods }) {
    state.goods = goods
  },

  [INCREASE_FOOD_COUNT](state, { food }) {
    // 如果该食物没有count属性,就添加一个; 如果有,就count+1
    if (!food.count) {
      Vue.set(food, "count", 1)
      //向购物车中加入该食物
      state.cartFoods.push(food)
    } else {
      food.count++
    }
  },
  [DECREASE_FOOD_COUNT](state, { food }) {
    // 防止用户快速点击时把count点成负数
    if (food.count > 0) {
      food.count--
      //如果减之后数量为零, 就从购物车中移除
      if (food.count === 0) {
        // 找到food在购物车中的索引
        let index = state.cartFoods.indexOf(food)
        state.cartFoods.splice(index, 1)
      }
    }
  },
  [CLEAR_CART](state) {
    state.cartFoods.forEach((food) => {
      food.count = 0
    })
    state.cartFoods = []
  },
}
